package com.googlecode.loframework.view
{
	import flash.display.DisplayObject;
	import flash.events.Event;
	
	import mx.containers.Canvas;
	import mx.events.FlexEvent;
	
	/**
	 * The starting point. Here pages are loaded and unloaded. 
	 * @author ~martin
	 * 
	 */
	public class PageHolder extends Canvas implements IPageHolder
	{
		/**
		 * A list of all loaded pages. 
		 */
		private var _pageList:Array;
		
		/**
		 * Event message.
		 */
		public static const PAGE_ADDED:String = "pageAdded";
		
		/**
		 * Constructor 
		 * 
		 */
		public function PageHolder()
		{
			_pageList = [];

		}
		
		/**
		 * Pages can be added in MXML by adding them as children within the <PageHolder> tags or programatically.
		 * All children of PageHolde are initally added to _pageList array, not the display list.
		 *  
		 * @param child
		 * @return 
		 * 
		 */
		override public function addChild(child:DisplayObject):DisplayObject
		{
			// check whether page is valid
			if(child is IPage == false)
			{
				throw(new Error("Added pages must implement com.googlecode.loframework.view.IPage"));
			}
			
			if(child is DisplayObject == false)
			{
				throw(new Error("Added pages must extend the DisplayObject class"));
			}
			
			// isLoaded remains false at this stage because the page has not been processed
			if((child as IPage).isLoaded == false)
			{
				// add child to list
				_pageList.push(child);

				dispatchEvent(new Event(PAGE_ADDED));
			}else
			{
				super.addChild(child);
			}

			return child;
		}
		
		/**
		 * Returns the current list of pages PageHolder contains.
		 * @return 
		 * 
		 */
		public function get pageList():Array{
			return _pageList;
		}
		
		/**
		 * Returns the number of pages in _pageList. 
		 * @return 
		 * 
		 */
		public function get numPages():int{
			return _pageList.length;
		}
		
		/**
		 * Loads a new page. 
		 * @param index
		 * 
		 */
		public function changePage(index:int):void
		{
			removeAllChildren();	

			addChild(_pageList[index] as DisplayObject);
		}
		
		/**
		 * Returns the currently loaded page. 
		 * @return 
		 * 
		 */
		public function get loadedPage():IPage
		{
			if(numChildren > 0)
			{
				return getChildAt(0) as IPage;
			}

			return null;
		}
	}
}